package 康复训练_JavaGo并驾齐驱;

import 二叉树.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Jz32II从上到下打印二叉树II {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.addLast(root);

        while (!queue.isEmpty()) {
            List<Integer> itemList = new ArrayList<>();
            int count = queue.size();
            while (count > 0) {
                count--;
                TreeNode firstNode = queue.removeFirst();
                itemList.add(firstNode.val);
                if (firstNode.left != null) {
                    queue.addLast(firstNode.left);
                }
                if (firstNode.right != null) {
                    queue.addLast(firstNode.right);
                }

            }
            result.add(itemList);
        }
        return result;
    }

}
